<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Home\Behavior;

/**
 * 360 safe 防注入脚本
 */
class SafeBehavior extends \Think\Behavior
{
    
    // 行为扩展的执行入口必须是run
    public function run (&$content)
    {
        $getfilter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?Select|Update.+?SET|Insert\\s+INTO.+?VALUES|(Select|Delete).+?FROM|(Create|Alter|Drop|TRUNCATE)\\s+(TABLE|DATABASE)";
        $postfilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?Select|Update.+?SET|Insert\\s+INTO.+?VALUES|(Select|Delete).+?FROM|(Create|Alter|Drop|TRUNCATE)\\s+(TABLE|DATABASE)";
        $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?Select|Update.+?SET|Insert\\s+INTO.+?VALUES|(Select|Delete).+?FROM|(Create|Alter|Drop|TRUNCATE)\\s+(TABLE|DATABASE)";
        foreach ($_GET as $key => $value)
        {
            $this->_stopAttack($key, $value, $getfilter);
        }
        foreach ($_POST as $key => $value)
        {
            $this->_stopAttack($key, $value, $postfilter);
        }
        foreach ($_COOKIE as $key => $value)
        {
            $this->_stopAttack($key, $value, $cookiefilter);
        }
    }

    protected function _stopAttack ($StrFiltKey, $StrFiltValue, $ArrFiltReq)
    {
        is_array($StrFiltValue) and $StrFiltValue = implode($StrFiltValue);
        if (preg_match("/" . $ArrFiltReq . "/is", $StrFiltValue) == 1)
        {
            \KCSLog::WARN("360 safe : " . $StrFiltKey . "_" . $StrFiltValue . "_" . $ArrFiltReq);
            redirect('/');
            exit();
        }
    }
} 